using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ReminderApp
{
    public partial class Reminder : Form
    {
        string from, to, intervalTemp;
        bool startWithWindow;
        ReminderAction ra;
        int interval;

        public Reminder()
        {
            InitializeComponent();
        }

        private void Reminder_Load(object sender, EventArgs e)
        {
            //Get Time Scale
            ra = new ReminderAction();

            ra.GetTimeScale(out from, out to, out intervalTemp, out startWithWindow);
            interval = int.Parse(intervalTemp) * 60;

            if (!startWithWindow)
            {
                Thread oThread = new Thread(Process);
                oThread.Start();
            }
            else
            {
                //start timer
                StartTimer(interval);
            }

            // Processes all the events in the queue.
            Application.DoEvents();
        }

        public void Process()
        {
            TimeSpan ts = DateTime.Now - DateTime.Parse(DateTime.Today.ToShortDateString() + " " + from);
            
            int numberOfWaitingSeconds = interval - ((int)ts.TotalSeconds - ((int)(ts.TotalSeconds / interval) * interval));
            
            Thread.Sleep(numberOfWaitingSeconds * 1000);

            //do reminding action
            ra.ShowTextMessage();
        }

        public void StartTimer(int interval)
        {
            myTimer.Interval = interval * 1000;
            myTimer.Start();
        }

        // This is the method to run when the timer is raised.
        private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            myTimer.Stop();
            myTimer.Enabled = true;
            
            if (DateTime.Now >= DateTime.Parse(DateTime.Today.ToShortDateString() + " " + from) && DateTime.Now <= DateTime.Parse(DateTime.Today.ToShortDateString() + " " + to))
            {
                //do reminding action
                ra.ShowTextMessage();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Reminder_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.Show();
        }
    }
}